package cn.jbt.advice;

import cn.jbt.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    /**
     * <h2>参数绑定异常拦截</h2>
     */
    @ExceptionHandler(value = BindException.class)
    public CommonResponse<String> handlerBindException(BindException e) {
        log.error("BindException: ", e);
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new CommonResponse<>(-1, objectError.getDefaultMessage());
    }

    /**
     * <h2>全局异常拦截</h2>
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResponse<String> handlerGlobalException(Exception e) {
        log.error("Exception: ", e);
        CommonResponse<String> response = new CommonResponse<>(-1, e.getMessage());
        response.setData("500 Internal Error!");
        return response;
    }

}
